<?php

/**
 * UserController is the default controller for this application
 */
class UserController extends ControllerBase {
	
	/**
	 * Admin User Data Service Object
	 * @var UserDataService object
	 */
	private $UserDataService;
	//public $CityDataService;
	/**
	 * UserController Constructor
	 */
	public function __construct() {
		parent::__construct ();
		
		// Set User name
		$this->setPageName ( 'admin_User' );
		
		// Init Authentication class
		$authentication = new Authentication ();
		
		// Only administrator can right
		if ($authentication->isAdministrator () == false) {
			
			// Go to login User
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Login/index';
			CommonUtils::redirect ( $url );
		}
		
		// Get status list of User category
		//$this->smarty->assign ( 'statusList', UserEntity::getStatusList() );
		
		// New User Data Service
		$this->UserDataService = new UserDataService ();
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing User of the site. Return list of all User category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function indexAction() {
		$this->smarty->assign('pageName', 'user');
		// View User_category list
		$this->listAction ();
	}
	
	/**
	 * Dispplay List of User_category
	 * landing User of the site. Return list of all User_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function listAction() {
		
		$arrElement = array ();
//		$arrElement ['status'] = UserEntity::ACTIVE;
		
		$numRecordPerPage = ITEM_PER_PAGE;
		
		// Pager
		$start = $this->getQuery ( 'start', 0 );
		if ($start == '' || $start < 0) {
			$start = 0;
		}
		
		// Get Totals Templates
		$totals = $this->UserDataService->getTotals ( $arrElement );
		
		$itemList = $this->UserDataService->getItems ( $arrElement, NULL, $start, $numRecordPerPage );
		
		if ($start > $totals) {
			$start = 0;
		}
		$link = Zend_Registry::get ( 'config' )->APPLICATION_URL . "/Admin/User/Index";
		$pageLink = '';
		if ($totals > $numRecordPerPage) {
			$pageUtils = new PagerUtils ( $start, $totals, $numRecordPerPage, 10, $link );
			$pageLink = $pageUtils->writePagesLinks ( 0, 'start' );
			$pageLink .= "<br><span class=\"paing_text_nolink\">" . $pageUtils->writePagesCounter () . "</span>";
		}
		
		$this->smarty->assign ( 'UserEntities', $itemList );
		$this->smarty->assign ( 'this', $this );
		$this->smarty->assign ( 'pageLink', $pageLink );
		//var_dump($itemList);
		// create session
		$this->createActionKey ();
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/User/index.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Add action is trigger when admin want to add the User_category information
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function addAction() {
		
		$isError = false;
		$msg = "";
		$userEntity = new UserEntity();
		$aUserType = $userEntity->getAllUserTypeList();

		// Get action method and check it
		$actionForm = $this->getPost ( 'submit', '' );

		if (! empty ( $actionForm )) 
		{
			// get email
			$email = $this->getPost('email','');
			$email = trim($email);
			if($this->UserDataService->checkExistEmail($email) == 1)
			{
				$isError = true;
				$msg = "Mail trùng";
			}else{
			// Get name field
			$fullname = $this->getPost ( 'fullname', "" );
			$fullname = trim ( $fullname );
			// get email
			$email = $this->getPost('email','');
			$email = trim($email);
			// get birthday
			$birthday = $this->getPost('birthday','');
			// get address
			$address = $this->getPost('address');
			//get phone
			$phone = $this->getPost('phone');
			// get password
			$password = $this->getPost('pass');
			// get picture
			$picture = '';
			try {
				$picture=CommonUtils::uploadPictureEx('picture');
			} catch (Exception $e) {
				$resultmessage = 'Không upload được hình';
			}
			// get gender
			$gender = $this->getPost('gender');
			// get status
			 UserEntity::ACTIVE;
			 $usertype=$this->getPost('userType');
			// check
			if (! empty ($fullname ) 
			  && !empty($email)
			  && !empty($birthday)
			  && !empty($address)
			  && !empty($phone)
			  && !empty($email)) {
				try {					
					// Init Authentication class
					$authentication = new Authentication ();
					$newpass= $authentication->randomPassword(6);
					// Save data into database
					$userEntity = $this->UserDataService->beforeCreate ();
					$userEntity->fullname = $fullname;
					$userEntity->email = $email;
					$userEntity->address = $address;
					$userEntity->gender = $gender;
					$userEntity->phone = $phone;
					$userEntity->password = $authentication->encryptPassword ( $newpass );
					$userEntity->status = UserEntity::ACTIVE;
					$userEntity->userType = $usertype;
					$userEntity->birthday = $birthday;
					$userEntity->picture = $picture;
					$userEntity->balance = 0;
					$UserId = $this->UserDataService->create ($userEntity );
					
					//send mail
					$mail = new SENDMAIL();
					$subject = 'Muahoi: Tài khoản đã được tạo';
					$body = '<p>Chào '.$fullname.'</p><p>Tài khoản đăng nhập của bạn, email: '.$email.', pass:'.$password.'. Với chức danh: '.$userEntity->getStatusName().'</p>';
					$res = $mail->send($email, $fullname, $subject, $body);
					if (!$res){
						$this->UserDataService->del($UserId);
						$isError = true;
						$msg = "Không thể tạo vì không gửi mail được";
					}else{
						// Redirect to edit User
						$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/User/';
						CommonUtils::redirect ( $url );
						exit ();
					}
				} catch ( Exception $ex ) {
					$isError = true;
					// Ignore to process this case. Only show a message
					$msg = 'The item cannot create successfully. Error Code = ' . $ex->getCode ();
					
					echo $ex->getMessage ();
				
				}
			} else {
				$isError = true;
				
				$msg = 'Please fill in all required fields';
			}
			}
		}
		
		// Create new token key
		$this->createActionKey ();
		$this->smarty->assign ( 'msg', $msg );
		$this->smarty->assign ( 'isError', $isError );
		$this->smarty->assign('aUserType', $aUserType);
		//$this->smarty->assign('userEntity',$userEntity);
		$this->smarty->assign ( 'fullname', isset ( $fullname ) ? $fullname : "" );
		$this->smarty->assign ( 'email', isset ( $email) ? $email : "" );
		$this->smarty->assign('address', isset($address)? $address: "");
		$this->smarty->assign('phone',isset($phone)? $phone: "");
		$this->smarty->assign('gender',isset($gender)? $gender: "");
		$this->smarty->assign('password', isset($password)? $password: "");
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/User/add.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Edit action is trigger when admin want to edit the User_category information
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function editAction() {
		// Error flag
		$isError = false;
		$msg = "";
		$userEntity = new UserEntity();
		$aUserType = $userEntity->getAllUserTypeList();
		// Get id of User
		$id = $this->getPost ( 'id' );
		if (empty ( $id )) {
			$id = $this->getQuery ( 'id' );
		}
		// If the id of User does not exist, go on to view list User
		if (empty ( $id ) || ! is_numeric ( $id )) {
			$this->listAction ();
			return false;
		}
		
		$id = intval ( $id );
			
		// Get data
		$userEntity = $this->UserDataService->getById($id );
		// check data
		if (empty ( $userEntity )) {
			$this->listAction ();
			return false;
		}
		// Get action method and check it
		$actionForm = $this->getPost ( 'submit', '' );
		
		// submit
		if (! empty ( $actionForm )) {
		// Get name field
			$fullname = $this->getPost ( 'fullname', "" );
			$fullname = trim ( $fullname );
			// get birthday
			$birthday = $this->getPost('birthday','');
			// get address
			$address = $this->getPost('address');
			//get phone
			$phone = $this->getPost('phone');
			// get password
			$password = $this->getPost('pass');
			// get picture
			$email = $this->getPost('email');
			$picture = '';
			try {
				$picture=CommonUtils::uploadPictureEx('picture');
			} catch (Exception $e) {
				$resultmessage = 'Không upload được hình';
			}
			// get gender
			$gender = $this->getPost('gender');
			// get status
			 UserEntity::ACTIVE;
			 $usertype=$this->getPost('userType');
			
			// check
			if (! empty ( $fullname )
			&& ! empty($phone)
			&& ! empty($email)) {
				try {
					$userEntity->fullname=$fullname;
					$userEntity->email=$email;
					$userEntity->address=$address;
					$userEntity->birthday=$birthday;
					$userEntity->password=$password;
					$userEntity->gender=$gender;
					$userEntity->userType=$usertype;
					$res = $this->UserDataService->update( $userEntity );
					//var_dump($res);
					$isError = false;
					
					// Show a message
					$msg = 'The record has been updated successfully';
					echo $msg;
					// Redirect to edit User
					$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/User/';
					CommonUtils::redirect ( $url );
					exit ();
				} catch ( Exception $ex ) {
					
					// Ignore to process this case. Only show a message
					$msg = 'The item cannot update successfully. Error Code = ' . $ex->getCode ();
					$isError = true;
				}
			} 
			
			else {
				$isError = true;
				$msg = 'Please fill in all required fields';
			}
			
		}
		
		// create session
		$this->createActionKey ();
		$this->smarty->assign ( 'msg', $msg );
		$this->smarty->assign ( 'isError', $isError );
		$this->smarty->assign('id',$userEntity->id);
		$this->smarty->assign ( 'fullname', $userEntity->fullname );
		$this->smarty->assign ( 'email', $userEntity->email);
		$this->smarty->assign('address',$userEntity->address);
		$this->smarty->assign('birthday',$userEntity->birthday);
		$this->smarty->assign('phone',$userEntity->phone);
		$this->smarty->assign('gender',$userEntity->gender);
		$this->smarty->assign('password',$userEntity->password);
		$this->smarty->assign('userType',$userEntity->userType);
		$this->smarty->assign('aUserType',$aUserType);		
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/User/edit.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Delete action is trigger when administrator want to delete a User_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function deleteAction() {
		// Get Id of User
		$id = $this->getPost ( 'idValue', 0 );
		
		if ($this->validateActionKey () && ! empty ( $id ) && is_numeric ( $id )) {
			
			$id = intval ( $id );
			// Delete User
			$res = $this->UserDataService->del ( $id );
		}
		$this->listAction ();
	}
	public function resendPassAction(){
		// get action key
		$actionKey= $this->getPost('actionKey','');
		// get user id
		$id = $this->getPost('idValue', '');
		// get userEntity by ID
		$userEntity = $this->UserDataService->getById($id);
		//var_dump($userEntity); die;
		$oldpassword = $userEntity->password;
		//echo $oldpassword;
		$authentication = new Authentication();
		$newpassword = $authentication->randomPassword(6);
		
		$userEntity->password = $authentication->encryptPassword($newpassword);
		//$userEntity->email = 'phuocloc1989@yahoo.com';
		$res= $this->UserDataService->update($userEntity);
		//echo $userEntity->password;
		$mail = new SENDMAIL();
		$check = $mail->send($userEntity->email, $userEntity->fullname,'password moi', $newpassword);
		//var_dump($check);
		if (!$check){
			//$oldpassword = $this->UserDataService->update($userEntity);
			
			$userEntity->password =$oldpassword;
			$res= $this->UserDataService->update($userEntity);
			//var_dump($res);
		}
		$this->listAction();
		
	}
	public function changePasswordAction(){
		$isError = false;
		$msg = "";
		$authentication = new Authentication();
		// get user id
		$user_id= $authentication->getCurrentUserId();
		$userDataService = new UserDataService ();
		$userEntity = $userDataService->getByID($user_id);
		//var_dump($userEntity);
		//var_dump($userEntity);
		$actionForm = $this->getPost ( 'submit', '' );
		if ($actionForm != '') {
				$currentpassword = $this->getPost('currentPassword','');
				if ($authentication->encryptPassword($currentpassword) == $userEntity->password){
						$newpassword = $this->getPost('newPassword','');
						$repassword = $this->getPost('reTypePassword','');
					if ($newpassword == $repassword){
						$userEntity->password = $authentication->encryptPassword($newpassword);
					}
					else {
						$isError = true;
						$msg = "Khong hop le";
					}
				}else {
					$isError = true;
					$msg ="khong hop le";
				}
			$res = $userDataService->update($userEntity);
			//var_dump($res);
//			$isError = false;
//			$msg="Cap nhat password thanh cong";
			// Redirect to edit Supplier
			$url = Zend_Registry::get('config')->APPLICATION_URL . '/Admin/';
			CommonUtils::redirect($url);
		}
		$this->smarty->assign('isError',$isError);
		$this->smarty->assign('msg',$msg);
		$this->smarty->assign('userEntity',$userEntity);
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/User/changepassword.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}

}
